import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Like } from '../../entities/like.entity';
import { Article } from '../../entities/article.entity';
import { ArticleService } from '../article/article.service';
import { ArticleResponseDto } from 'src/dto/article.dto';

@Injectable()
export class LikeService {
  [x: string]: any;
  constructor(
    @InjectRepository(Like)
    private likeRepository: Repository<Like>,
    @InjectRepository(Article)
    private articleRepository: Repository<Article>,
    private articleService: ArticleService,
  ) {}

  async createLike(userId: number, articleId: number) {
    // 检查文章是否存在
    // const article = await this.articleRepository.findOneBy({ id: articleId });
    const articleResponse = await this.articleService.findOne(articleId);
    if (!articleResponse) {
      throw new NotFoundException('文章不存在');
    }

    // 检查是否已经点赞
    const existingLike = await this.likeRepository.findOneBy({
      userId,
      articleId
    });

    if (existingLike) {
      throw new ConflictException('您已经点赞过这篇文章');
    }

    // 创建点赞记录
    const like = this.likeRepository.create({
      userId,
      articleId,
      createdAt: new Date(),
    });

    await this.likeRepository.save(like);

    // 更新文章点赞数
    await this.updateArticleLikeCount(articleId);

    return { success: true, message: '点赞成功' };
  }

  async removeLike(userId: number, articleId: number) {
    // 检查点赞记录是否存在
    const like = await this.likeRepository.findOneBy({
      userId,
      articleId
    });

    if (!like) {
      throw new NotFoundException('您还没有点赞过这篇文章');
    }

    // 删除点赞记录
    await this.likeRepository.remove(like);

    // 更新文章点赞数
    await this.updateArticleLikeCount(articleId);

    return { success: true, message: '取消点赞成功' };
  }

  async toggleLike(userId: number, articleId: number) {
    // 检查文章是否存在
    const article = await this.articleRepository.findOneBy({ id: articleId });
    if (!article) {
      throw new NotFoundException('文章不存在');
    }

    // 检查是否已经点赞
    const existingLike = await this.likeRepository.findOneBy({
      userId,
      articleId
    });

    if (existingLike) {
      // 如果已经点赞，则取消点赞
      await this.likeRepository.remove(existingLike);
      await this.updateArticleLikeCount(articleId);
      return { success: true, liked: false, message: '取消点赞成功' };
    } else {
      // 如果未点赞，则创建点赞
      const like = this.likeRepository.create({
        userId,
        articleId,
        createdAt: new Date(),
      });
      await this.likeRepository.save(like);
      await this.updateArticleLikeCount(articleId);
      return { success: true, liked: true, message: '点赞成功' };
    }
  }

  async getUserLikes(userId: number) {
    const userinfo: Like[] = await this.likeRepository.find({
      where: { userId },
      order: { createdAt: 'DESC' },
    });
    // console.log("获取用户点赞列表userinfo:", userinfo);
    let arrs: ArticleResponseDto[] = [];

    // 使用for...of循环正确处理异步操作
    for (const item of userinfo) {
      try {
        // 尝试获取文章信息
        const article = await this.articleService.findOne(item.articleId);
        // 只有查询成功时才添加到数组中
        arrs.push(article);
        console.log(`文章ID ${item.articleId} ====== ${JSON.stringify(article)}`);
      } catch (err) {
        // 查询失败时静默跳过，不影响其他文章的查询
        console.log(`文章ID ${item.articleId} 未找到，已跳过`);
      }
    }
    
    return { success: true, message: '获取用户点赞成功', data: arrs };
  }

  async getArticleLikes(articleId: number) {
    return this.likeRepository.find({
      where: { articleId },
      order: { createdAt: 'DESC' },
    });
  }

  async isArticleLikedByUser(userId: number, articleId: number) {
    const like = await this.likeRepository.findOneBy({
      userId,
      articleId
    });
    return !!like;
  }

  private async updateArticleLikeCount(articleId: number) {
    // 更新文章的点赞数
    const query = `
      UPDATE article a 
      SET likeCount = (SELECT COUNT(*) FROM \`like\` l WHERE l.articleId = a.id)
      WHERE a.id = ?
    `;
    await this.articleRepository.query(query, [articleId]);
  }
}
